package com.wocao.framework.exception;

import com.wocao.commom.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理器
 *
 * @author sunhao
 * @date 2021/10/29
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public Result<Void> handleBindException(BindException e) {
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return Result.ERROR(message);
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public Result<Void> handleBindException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("GlobalExceptionHandler.exception URL={}", requestURI, e);
        return Result.ERROR(e.getMessage());
    }

    /**
     * 登录异常
     */
    @ExceptionHandler(UsernameNotFoundException.class)
    public Result<Void> handleBindException(UsernameNotFoundException e) {
        log.error("GlobalExceptionHandler.usernameNotFoundException.", e);
        return Result.ERROR(e.getMessage());
    }

}
